/**
 * @version 2007-5-22
 * @author xalinx at gmail dot com
 */
package org.nanhill.vest.component;

import java.util.ArrayList;
import java.util.List;

import org.nanhill.vest.layout.Layout;

/**
 * @version 2007-5-22
 * @author xalinx at gmail dot com
 * 
 */

public abstract class AbstractComponent implements Component {
	@SuppressWarnings("unchecked")
	private List<Object> components;

	private Layout layout;

	public void setLayout(Layout layout) {
		this.layout = layout;
	}

	public Layout getLayout() {
		return layout;
	}

	protected Component addChild(Component comp) {
		addComponent(comp);
		return this;
	}

	public void clearChildren() {
		if (null != components) {
			components.clear();
		}
	}

	public Object getChild(int id) {
		if (components == null || components.isEmpty()) {
			return null;
		}
		return components.get(id);
	}

	public Component addChild(Dynamic dynamic) {
		addComponent(dynamic);
		return this;
	}

	private void addComponent(Object obj) {
		if (components == null) {
			components = new ArrayList<Object>(64);
		}
		components.add(obj);
	}

	public List<Object> getChildren() {
		return components;
	}

	public void buildInner(Builder builder) {
		if (null == components) {
			return;
		}
		for (Object obj : components) {
			if (obj instanceof Component) {
				Component comp = (Component) obj;
				comp.build(builder);
			} else if (obj instanceof Dynamic) {
				Dynamic dy = (Dynamic) obj;
				builder.append(dy);
			} else {
				throw new IllegalStateException();
			}
		}
	}

}
